package com.dindang.maintenance.mvp.ui.widget;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.dindang.maintenance.R;
import com.dindang.maintenance.app.utils.JsonReadUtils;
import com.dindang.maintenance.app.utils.TimeComparisonUtils;
import com.dindang.maintenance.mvp.model.entity.MaintainFiltrate;
import com.jess.arms.utils.ArmsUtils;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by cxw on & 2018/11/8
 */
public class AdvanceSearchDialog extends Dialog {

    private final static String maintenanceManagementFilterData = "maintenanceManagementFilterData.json";

    public AdvanceSearchDialog(@NonNull Context context) {
        super(context);
    }

    public AdvanceSearchDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);
    }

    protected AdvanceSearchDialog(@NonNull Context context, boolean cancelable, @Nullable OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
    }

    public static class Builder{
        private Context context;
        private OnClickListener listener;
        private List<MaintainFiltrate.Category> categoryList;// 左边的分类
        private MaintainCategoryViewAdapter categoryAdapter;// 左边分类适配器
        private List<MaintainFiltrate.Item> itemList;// 右边的分类
        private MaintainConditionViewAdapter conditionAdapter;// 右边的分类适配器
        private TimePickerView pvCustomTime;
        private int mPosition = 0;
        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        Calendar startDate = Calendar.getInstance();
        Calendar startStartDate = Calendar.getInstance();
        Calendar startEndDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();
        Calendar endStartDate = Calendar.getInstance();
        Calendar endEndDate = Calendar.getInstance();

        public Builder(Context context) {
            this.context = context;
        }

        public Builder setListener(OnClickListener listener) {
            this.listener = listener;
            return this;
        }

        private TextView tv_reset;
        private TextView tv_search;
        private RecyclerView rv_category;
        private RecyclerView rv_conditions;

        private AdvanceSearchDialog dialog;

        public AdvanceSearchDialog create() {
            dialog = new AdvanceSearchDialog(context);
            View view = LayoutInflater.from(context).inflate(R.layout.maintenance_dialog_filtrate, null);
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);//加上这一句，取消原来的标题栏，没加这句之前，发现在三星的手机上会有一条蓝色的线
            dialog.setContentView(view, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            tv_reset = view.findViewById(R.id.maintenance_tv_reset);
            tv_search = view.findViewById(R.id.maintenance_tv_search);
            rv_category = view.findViewById(R.id.maintenance_rv_category);
            rv_conditions = view.findViewById(R.id.maintenance_rv_conditions);
            reset();
            tv_search.setOnClickListener(v -> listener.onSearch(categoryList));
            tv_reset.setOnClickListener(v -> reset());
            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            return dialog;
        }

        public void dismiss(){
            if(dialog != null){
                dialog.dismiss();
            }
        }

        public void show(){
            dialog.show();
        }

        class MaintainCategoryViewAdapter extends RecyclerView.Adapter<MaintainCategoryViewAdapter.ViewHolder> {

            @NonNull
            @Override
            public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.maintenance_item_filtrate_category, parent, false);
                MaintainCategoryViewAdapter.ViewHolder viewHolder = new MaintainCategoryViewAdapter.ViewHolder(view);
                return viewHolder;
            }

            @Override
            public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
                MaintainFiltrate.Category category = categoryList.get(position);
                holder.tv_category.setText(category.name);
                if(category.isSelect){
                    holder.tv_category.setBackgroundColor(ArmsUtils.getColor(context, R.color.maintenance_gray2));
                }else{
                    holder.tv_category.setBackgroundColor(ArmsUtils.getColor(context, R.color.maintenance_color_white));
                }
                holder.tv_category.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        for (MaintainFiltrate.Category c : categoryList) {
                            c.isSelect = false;
                        }
                        category.isSelect = true;
                        mPosition = position;
                        itemList = category.item;
                        categoryAdapter.notifyDataSetChanged();
                        conditionAdapter.notifyDataSetChanged();

                        if(null != listener){
                            listener.onRequestData(category);
                        }
                    }
                });
            }

            @Override
            public int getItemCount() {
                return categoryList.size();
            }

            class ViewHolder extends RecyclerView.ViewHolder {
                TextView tv_category;
                ViewHolder(View itemView) {
                    super(itemView);
                    tv_category = itemView.findViewById(R.id.maintenance_tv_category);
                }
            }

        }

        public void refreshCategoryAndItem(){
            categoryAdapter.notifyDataSetChanged();
            conditionAdapter.notifyDataSetChanged();
        }

        class MaintainConditionViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

            public static final int TYPE_SELECT = 1;
            public static final int TYPE_DATE = 2;

            @Override
            public int getItemViewType(int position) {
                if ("date".equals(itemList.get(position).type)) {
                    return TYPE_DATE;
                } else {
                    return TYPE_SELECT;
                }
            }

            @NonNull
            @Override
            public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                View view;
                if(viewType == TYPE_DATE){// 日期选择
                    view = LayoutInflater.from(parent.getContext()).inflate(R.layout.maintenance_item_filtrate_condition_date, parent, false);
                    return new DateViewHolder(view);
                }else{
                    view = LayoutInflater.from(parent.getContext()).inflate(R.layout.maintenance_item_filtrate_condition, parent, false);
                    return new SelectViewHolder(view);
                }
            }

            @Override
            public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
                MaintainFiltrate.Item item = itemList.get(position);
                if (holder instanceof DateViewHolder) {
                    DateViewHolder dateViewHolder = (DateViewHolder) holder;

                    dateViewHolder.tv_startdate.setText(TextUtils.isEmpty(item.startValue) ? item.startTimeHint : item.startValue);
                    dateViewHolder.tv_enddate.setText(TextUtils.isEmpty(item.endValue) ? item.endTimeHint : item.endValue);

                    dateViewHolder.tv_startdate.setOnClickListener(v -> dialogStartDateTime("请选择开始日期", item));

                    dateViewHolder.tv_enddate.setOnClickListener(v -> dialogEndDateTime("请选择结束日期", item));
                } else {
                    SelectViewHolder selectViewHolder = (SelectViewHolder) holder;
                    selectViewHolder.tv_name.setText(item.name);
                    if(item.isSelect){
                        selectViewHolder.iv_select.setVisibility(View.VISIBLE);
                    }else{
                        selectViewHolder.iv_select.setVisibility(View.GONE);
                    }
                    selectViewHolder.ll_normal_select.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            for (MaintainFiltrate.Item i : itemList) {
                                i.isSelect = false;
                                if("date".equals(i.type)){
                                    i.startValue = "";
                                    i.endValue = "";
                                }
                            }
                            item.isSelect = true;
                            categoryList.get(mPosition).value = item.name;
                            conditionAdapter.notifyDataSetChanged();
                        }
                    });
                }
            }

            @Override
            public int getItemCount() {
                return itemList.size();
            }

            class SelectViewHolder extends RecyclerView.ViewHolder {
                LinearLayout ll_normal_select;
                TextView tv_name;
                ImageView iv_select;
                SelectViewHolder(View itemView) {
                    super(itemView);
                    ll_normal_select = itemView.findViewById(R.id.maintenance_ll_item);
                    tv_name = itemView.findViewById(R.id.maintenance_tv_name);
                    iv_select = itemView.findViewById(R.id.maintenance_iv_select);
                }
            }

            class DateViewHolder extends RecyclerView.ViewHolder {
                TextView tv_startdate;
                TextView tv_enddate;
                DateViewHolder(View itemView) {
                    super(itemView);
                    tv_startdate = itemView.findViewById(R.id.maintenance_tv_startdate);
                    tv_enddate = itemView.findViewById(R.id.maintenance_tv_enddate);
                }
            }

        }

        /**
         * 时间选择开始
         * @param title
         * @param item
         */
        private void dialogStartDateTime(String title, MaintainFiltrate.Item item) {
            //时间选择器 ，自定义布局
            pvCustomTime = new TimePickerBuilder(context, new OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {//选中事件回调
                    if(date.getTime() > item.endTime.getTime()){
                        ArmsUtils.makeText(context.getApplicationContext(), "开始时间不能大于结束时间");
                        return;
                    }
                    startDate.setTime(date);
                    endStartDate.setTime(date);
                    item.startTime = date;
                    item.startValue = TimeComparisonUtils.dateTString(date);

                    for (MaintainFiltrate.Item i : categoryList.get(mPosition).item)
                        i.isSelect = false;
                    item.isSelect = true;
                    categoryList.get(mPosition).value = "开始时间:" + item.startValue + " 结束时间:" + item.endValue;

                    conditionAdapter.notifyDataSetChanged();
                    pvCustomTime.dismiss();
                }
            })
            .setDate(startDate)
            .setRangDate(startStartDate, startEndDate)
            .setLayoutRes(R.layout.maintenance_pickerview_custom_time, new CustomListener() {

                @Override
                public void customLayout(View v) {
                    final TextView tvSubmit = v.findViewById(R.id.maintenance_tv_finish);
                    final TextView tvTitle = v.findViewById(R.id.maintenance_tv_title);
                    tvTitle.setText(title);
                    ImageView ivCancel = v.findViewById(R.id.maintenance_iv_dialog_close);
                    tvSubmit.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            pvCustomTime.returnData();
                        }
                    });
                    ivCancel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            pvCustomTime.dismiss();
                        }
                    });
                }
            })
            .setContentTextSize(16)
            .setType(new boolean[]{true, true, true, true, true, false})
            .setLabel("年", "月", "日", "时", "分", "秒")
            .setLineSpacingMultiplier(3f)
            .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
            .setDividerColor(0xFFd1d1d1)
            .isDialog(true)
            .build();

            pvCustomTime.show();
        }

        /**
         * 时间选择结束
         * @param title
         * @param title
         */
        private void dialogEndDateTime(String title, MaintainFiltrate.Item item) {
            //时间选择器 ，自定义布局
            pvCustomTime = new TimePickerBuilder(context, new OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {//选中事件回调
                    if(date.getTime() < item.startTime.getTime()){
                        ArmsUtils.makeText(context.getApplicationContext(), "结束时间不能小于开始时间");
                        return;
                    }

                    endDate.setTime(date);
                    startEndDate.setTime(date);
                    item.endTime = date;
                    item.endValue = TimeComparisonUtils.dateTString(date);

                    for (MaintainFiltrate.Item i : categoryList.get(mPosition).item)
                        i.isSelect = false;
                    item.isSelect = true;
                    categoryList.get(mPosition).value = "开始时间:" + item.startValue + " 结束时间:" + item.endValue;

                    conditionAdapter.notifyDataSetChanged();
                    pvCustomTime.dismiss();
                }
            })
            .setDate(endDate)
            .setRangDate(endStartDate, endEndDate)
            .setLayoutRes(R.layout.maintenance_pickerview_custom_time, new CustomListener() {

                @Override
                public void customLayout(View v) {
                    final TextView tvSubmit = v.findViewById(R.id.maintenance_tv_finish);
                    final TextView tvTitle = v.findViewById(R.id.maintenance_tv_title);
                    tvTitle.setText(title);
                    ImageView ivCancel = v.findViewById(R.id.maintenance_iv_dialog_close);
                    tvSubmit.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            pvCustomTime.returnData();
                        }
                    });
                    ivCancel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            pvCustomTime.dismiss();
                        }
                    });
                }
            })
            .setContentTextSize(16)
            .setType(new boolean[]{true, true, true, true, true, false})
            .setLabel("年", "月", "日", "时", "分", "秒")
            .setLineSpacingMultiplier(3f)
            .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
            .setDividerColor(0xFFd1d1d1)
            .isDialog(true)
            .build();

            pvCustomTime.show();
        }

        /**
         * 重置
         */
        private void reset(){
            mPosition = 0;
            startStartDate.set(2010,0,1,0,0);
            startEndDate.set(selectedDate.get(Calendar.YEAR) + 10, 11, 31);
            endStartDate.set(2010,0,1,0,0);
            endEndDate.set(selectedDate.get(Calendar.YEAR) + 10, 11, 31);

            String oaJson = JsonReadUtils.getJsonStr(context, maintenanceManagementFilterData);
            categoryList = JSON.parseArray(oaJson, MaintainFiltrate.Category.class);
            categoryAdapter = new MaintainCategoryViewAdapter();
            rv_category.setAdapter(categoryAdapter);

            itemList = categoryList.get(mPosition).item;
            conditionAdapter = new MaintainConditionViewAdapter();
            rv_conditions.setAdapter(conditionAdapter);
        }

        /**
         * 销毁内容
         */
        public void onDestroy () {
            this.categoryList = null;
            this.categoryAdapter = null;
            this.itemList = null;
            this.conditionAdapter = null;
            this.pvCustomTime = null;
            this.selectedDate = null;
            this.startDate = null;
            this.startStartDate = null;
            this.startEndDate = null;
            this.endDate = null;
            this.endStartDate = null;
            this.endEndDate = null;
        }
    }

    @Override
    public void show() {
        super.show();
        WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
        layoutParams.gravity = Gravity.BOTTOM;
        layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
        layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        getWindow().getDecorView().setPadding(0, 0, 0, 0);
        getWindow().setAttributes(layoutParams);
    }

    public interface OnClickListener {
        void onSearch(List<MaintainFiltrate.Category> categorys);
        void onRequestData(MaintainFiltrate.Category category);
    }

}
